package org.megha.blog.example.io;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * Reads a file and writes unique words as output into another.
 * 
 * @author megha birmiwal
 */
public class UniqueWords {

	public static void main(String args[]) throws IOException {
		if (args.length != 2) {
			System.out.println("please provide two file names: <infile> <outfile>");
			return;
		}
		
		FileReader fileReader = null;
		try {
			fileReader = new FileReader(args[0]);
		} catch (FileNotFoundException e) {
			System.out.println("file not found: " + e.getMessage());
			return;
		}
		LinesReader lineReader = new LinesReader(fileReader);
		List<String> readLines = null;
		try {
			readLines = lineReader.readAllLines();
		} catch (IOException e) {
			System.out.println("IOException while reading from file: " + e.getMessage());
			return;
		} finally {
			fileReader.close();
		}
		// Prints all the lines in the file
//		for (String line : readLines) {
//			System.out.println(line);
//		}

		// Get all the unique words and save in a file
		Set<String> uniquewords = new HashSet<String>();
		for (String line : readLines) {
 			String[] words = line.split("[ ;,/\\(\\)\\[\\]\"\\t]");
			for(String word : words) {
				uniquewords.add(word);
			}
		}

		Writer writer = new FileWriter(args[1]);
		try {
			for(String word : uniquewords) {
	//			System.out.println(word);
				writer.write(word + "\n");
			}
		} finally {
			writer.close();
		}
	}
}

